package com.lwj.test.json;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.lwj.test.date.DateTools;

public class JsonUtils {

    public String getList4Json(List<Map<String, String>> list){
	StringBuffer jsonBuffer = new StringBuffer();
	if(list==null){
	    return "[]";
	}
	for (Map<String, String> map : list) {
	    jsonBuffer.append(getMap4Json(map)).append(",");
	}
	if(jsonBuffer.length()>0){
	    jsonBuffer.deleteCharAt(jsonBuffer.length()-1).insert(0, "[").append("]");
	}
	return jsonBuffer.toString();
    }
    
    public String getMap4Json(Map<String, String> map) {
	StringBuffer jsonBuffer = new StringBuffer();
	if (map==null) {
	    return "{}";
	}
	Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
	while (iterator.hasNext()) {
	    Entry<String, String> entry = (Entry<String, String>) iterator.next();
	    jsonBuffer.append("\""+entry.getKey()+"\""+":\""+entry.getValue()+"\",");
	}
	if(jsonBuffer.length()>0){
	    jsonBuffer.deleteCharAt(jsonBuffer.length()-1).insert(0, "{").append("}");
	}
	return jsonBuffer.toString();
    }
    
    public static void main(String[] args){
	JsonUtils utils = new JsonUtils();
	List<Map<String, String>> list = new ArrayList<Map<String,String>>();
	List<Map<String, String>> list2 = new LinkedList<Map<String,String>>();
	Map<String, String> map = null;
	
	for(int i=0;i<300000;i++){
	    map = new HashMap<String, String>();
	    map.put("id"+i, i+"");
	    map.put("user"+i, "--"+i);
	    list.add(map);
	    //list2.add(map);
	    //System.out.println(utils.getMap4Json(map));
	}
	System.out.println("start:"+DateTools.getDetailStrFromDate(new Date()));
	utils.getList4Json(list);
	System.out.println("end:"+DateTools.getDetailStrFromDate(new Date()));
	//System.out.println("start:"+DateTools.getDetailStrFromDate(new Date()));
	//utils.getList4Json(list2);
	//System.out.println("end:"+DateTools.getDetailStrFromDate(new Date()));
	//System.out.println(utils.getMap4Json(null));
	
    }
}
